"""
双均线策略(backtrader实现)
策略逻辑：
1. 当短期均线上穿长期均线时买入
2. 当短期均线下穿长期均线时卖出
"""

import backtrader as bt

class DualMAStrategy(bt.Strategy):
    params = (
        ('fast', 10),  # 短期均线周期
        ('slow', 30)   # 长期均线周期
    )

    def __init__(self):
        # 初始化均线指标
        self.ma_fast = bt.indicators.SMA(period=self.p.fast)
        self.ma_slow = bt.indicators.SMA(period=self.p.slow)
        self.crossover = bt.indicators.CrossOver(self.ma_fast, self.ma_slow)

    def next(self):
        if not self.position:  # 没有持仓
            if self.crossover > 0:  # 金叉
                self.buy()  # 买入
        elif self.crossover < 0:  # 死叉
            self.close()  # 卖出

if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(DualMAStrategy)
    # 这里添加数据和其他配置
    cerebro.run()